﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using Film.Repository;
using Film.Common;
using System.Configuration;
using codeding.KMeans.DataStructures;
using codeding.KMeans.DataStructures.Lists;

namespace PhuongDoAn.Admin.Film
{
    public partial class Edit : AdminWebBase
    {
        public int ID = 0;
        public string _hour = "0";
        public string _minute = "0";
        public string _second = "0";
        public string _genre = "";

        protected void Page_Load(object sender, EventArgs e)
        {
            form1.Attributes.Add("enctype", "multipart/form-data");

            ////tinh thang ID dua tren query tim duoc!
            if (Request.QueryString["ItemID"] != null)
            {
                int.TryParse(Request.QueryString["ItemID"].ToString(), out ID);
            }

            if (!IsPostBack && !X.IsAjaxRequest)
            {
                try
                {
                    InitData();
                }
                catch (Exception ex)
                {
                    THONG_BAO_CAP_NHAT("Lỗi : " + ex.Message);
                }
            }
            LoadControl();
        }


        #region InitData

        private void InitData()
        {
            //Thêm cái năm vào
            for (int i = 1990; i < DateTime.Now.Year + 2; i++)
            {
                cbYear.Items.Add(new Ext.Net.ListItem(i.ToString()));
            }

            tblCountryRepository countryRepository = new tblCountryRepository();
            List<tblCountry> listCountry = countryRepository.GetAll();
            foreach (tblCountry country in listCountry)
            {
                cbCountry.Items.Add(new Ext.Net.ListItem(country.CountryName, country.CountryID.ToString()));
            }

            if (ID == 0)
            {
                btnCapNhat.Disabled = true;
                txtMovieName.Focus(true, 100);
            }
            if (ID > 0)
            {
                InitLoadAction();
            }
        }

        private void InitLoadAction()
        {
            ////thuc hien tim van ban o day va thuc hien
            tblMovieRepository movieRepository = new tblMovieRepository();
            tblMovie entity = movieRepository.Get(ID);
            if (entity == null)
            {
                //Dong lai cai form nay luon
                Page.Response.Redirect(ConfigKey.ERROR_URL);
                return;
            }

            int hour, minute, second;

            Util.ParseTime(entity.Runtime, out hour, out minute, out second);
            _hour = hour.ToString();
            _minute = minute.ToString();
            _second = second.ToString();

            _genre = entity.Genre;

            chkStatus.Checked = entity.Status;
            txtMovieName.Text = HttpUtility.HtmlEncode(entity.MovieName);
            txtDirector.Text = HttpUtility.HtmlEncode(entity.Director);

            cbYear.SelectedItem.Text = entity.Year.ToString();
            cbCountry.SelectedItem.Value = entity.CountryID.ToString();

            if (entity.ImageUrl != "")
            {
                string folder = ConfigurationManager.AppSettings["folderPath"];
                lblEditFile.Html = "<img src='" + folder + "/" + entity.ImageUrl + "' width='100px' height='100px' />";
            }
            else
            {
                lblEditFile.Html = "<img src='/Theme/Images/no-image.jpg' width='100px' height='100px' />";
            }

        }

        private void LoadControl()
        {
            for (int i = 0; i < 100; i++)
            {
                cbHour.Items.Add(new Ext.Net.ListItem(i.ToString(), i.ToString()));
            }
            cbHour.Value = _hour;

            for (int i = 0; i < 60; i++)
            {
                cbMinute.Items.Add(new Ext.Net.ListItem(i.ToString(), i.ToString()));
            }
            cbMinute.Value = _minute;

            for (int i = 0; i < 60; i++)
            {
                cbSecond.Items.Add(new Ext.Net.ListItem(i.ToString(), i.ToString()));
            }
            cbSecond.Value = _second;

            //Lay cac 
            tblGenreRepository genreRepository = new tblGenreRepository();
            List<tblGenre> listGenreAll = genreRepository.GetAll();
            Checkbox chk;
            foreach (tblGenre item in listGenreAll)
            {
                chk = new Checkbox();
                chk.ID = item.ID.ToString();
                chk.BoxLabel = item.Title;

                if (_genre.Contains("|" + item.Title))
                {
                    chk.Checked = true;
                }

                chgGenre.Items.Add(chk);

            }

        }

        #endregion InitData


        #region Save Data

        public void onSave(object sender, DirectEventArgs e)
        {
            try
            {
                tblMovieRepository movieRepository = new tblMovieRepository();
                tblMovie entity = new tblMovie();
                if (ID > 0)
                {
                    entity = movieRepository.Get(ID);
                }
                int iCountryID = 0;
                int.TryParse(cbCountry.Value.ToString(), out iCountryID);
                entity.CountryID = iCountryID;
                entity.Director = txtDirector.Text.Trim();
                entity.Status = chkStatus.Checked;
                entity.Year = int.Parse(cbYear.SelectedItem.Text);

                entity.MovieName = txtMovieName.Text.Trim();

                double hour = double.Parse(cbHour.SelectedItem.Text);
                double minute = double.Parse(cbMinute.SelectedItem.Text);
                double second = double.Parse(cbSecond.SelectedItem.Text);


                entity.Runtime = hour * 60 * 60 + minute * 60 + second;
                entity.SumRating = 0;
                entity.TotalRating = 0;
                //chgGenre
                string result = "";
                chgGenre.CheckedItems.ForEach(delegate(Checkbox checkbox)
                {
                    result = result + "|" + checkbox.BoxLabel;
                });
                entity.Genre = result;

                entity.ModifiedDate = DateTime.Now;
                //Tải file đính kèm
                string filePath = "";
                if (FileField.Value != null)
                {
                    string folder = ConfigurationManager.AppSettings["folderPath"];
                    folder = Server.MapPath(folder);

                    HttpFileCollection fileuploads = null;
                    fileuploads = HttpContext.Current.Request.Files;
                    filePath = Util.SaveFileWithoutOverwrite(fileuploads[0], folder);



                }
                entity.ImageUrl = filePath;

                if (ID == 0)
                {
                    entity.MovieID = DanhMucMovie.GetMaxID() + 1;
                    movieRepository.Add(entity);
                }
                else
                {
                    //  movieRepository.Update(entity);
                }
                movieRepository.SubmitChanges();
                ResourceManager1.RegisterClientScriptBlock("hideForm", "ReloadAddOrEdit();");
            }
            catch (Exception ex)
            {
                THONG_BAO_CAP_NHAT("Lỗi : " + ex.Message);
            }
        }

        #endregion Save Data

        #region ShowLanguage
        protected override void OnPreRender(EventArgs e)
        {
            if (!IsPostBack)
            {
                showLanguage();
            }
        }
        private void showLanguage()
        {

            btnCapNhat.DirectEvents.Click.EventMask.Msg = "Đang cập nhật dữ liệu, vui lòng chờ...";
            btnCapNhat.Text = "Lưu";
            ValidationStatus1.HideText = "Click để ẩn thông báo";
            ValidationStatus1.ShowText = "[ Dữ liệu nhập chưa đúng ]";
        }
        #endregion ShowLanguage
    }
}